import {onMounted, ref} from 'vue';
import {
	addBaseDataPlanApi,
	allRouteApi,
	deleteBaseDataPlanApi,
	editBaseDataPlanApi,
	issuePlan,
	lineAll,
	materialBomApi,
	productAll,
	productBaseDataPlanApi,
	ProductionPlanDetailApi
} from '@/api/production/productionPlan';
import {ElMessage, ElMessageBox} from 'element-plus'; // 假设使用 Element Plus

interface BaseDataPlanRecord {
	extension?: Record<string, any>;
	id: string;
	createTime?: string;
	updateUser?: string;
	updateTime?: string;
	createUser?: string;
	planNo: string;
	name: string;
	planBeginTime: string;
	planEndTime: string;
	actualBeginTime: string;
	actualEndTime: string;
	organizationId: string;
	status: number;
	type: string;
	description?: string;
	activate?: boolean;
	isDeleted?: boolean;
	clazz?: string;
}

interface BaseDataPlanPageResult {
	records: BaseDataPlanRecord[];
	total: number;
	size: number;
	current: number;
	optimizeCountSql: boolean;
	searchCount: boolean;
	pages: number;
}

interface ApiResponse<T> {
	code: number;
	message: string;
	data: T;
}

const buildTree = (items: any) => {
	const itemMap = {};
	const rootItems = [];
	items.forEach((item) => {
		itemMap[item.id] = {
			...item,
			value: item.id,
			label: item.orgName,
			name: item.orgName,
			children: []
		};
	});
	items.forEach((item) => {
		if (!item.parentId || item.parentId === '0') {
			rootItems.push(itemMap[item.id]);
		} else {
			if (itemMap[item.parentId]) {
				itemMap[item.parentId].children.push(itemMap[item.id]);
			}
		}
	});

	return rootItems;
};

export function useBaseDataPlanData() {
	const searchParam = ref({});
	const isLoading = ref(true);
	const searchFields = ref([
		{
			name: 'planNo',
			label: '计划编号',
			component: 'input',
			placeholder: '',
			class: '!w-[350px]'
		}
	]);
	const pageSize = ref(10);
	const current = ref(1);
	const pageTotal = ref(0);
	const paginatedData = ref<BaseDataPlanRecord[]>([]);
	const productData = ref([]);
	const allRouteData = ref([]);
	const materialData = ref([]);
	const lineListAll = ref([]);
	const lineGroup = ref([]);

	const typeData = ref([
		{ label: '销售计划', value: '1' },
		{ label: '备库计划', value: '2' },
		{ label: '返修计划', value: '3' }
	]);
	// 构建树形结构

	const fetchAll = async () => {
		await productAll({}).then((res) => {
			console.log(res, 'productAll');

			productData.value = res.data;
		});
		await allRouteApi({}).then((res) => {
			console.log(res, 'allRouteApi');

			allRouteData.value = res.data.records;
		});
		await materialBomApi({}).then((res) => {
			materialData.value = res.data.records;
		});

	};
	const fetchPageData = async (params: any) => {
		isLoading.value = true;
		try {
			const response = (await productBaseDataPlanApi({
				...params,
				current: current.value,
				pageSize: pageSize.value
			})) as unknown as ApiResponse<BaseDataPlanPageResult>;

			if (response.code === 200) {
				const { records, total } = response.data;
				paginatedData.value = records.map((i) => {
					return { ...i, family: [{}] };
				});
				pageTotal.value = total;
			} else {
				console.error('Error fetching data:', response.message);
			}
		} catch (error) {
			console.error('Error fetching data:', error);
		} finally {
			isLoading.value = false;
		}
	};

	onMounted(() => {
		fetchPageData(searchParam.value);
		fetchAll();
	});

	const handleSearch = () => {
		fetchPageData(searchParam.value);
	};

	const handleSizeChange = (val: number) => {
		pageSize.value = val;
		fetchPageData(searchParam.value);
	};

	const handleCurrentChange = (val: number) => {
		current.value = val;
		fetchPageData(searchParam.value);
	};

	const addBaseDataPlan = async (
		data: Partial<BaseDataPlanRecord>,
		callback: () => void
	) => {
		try {
			const url = data?.id ? editBaseDataPlanApi : addBaseDataPlanApi;
			const response = (await url(data)) as unknown as ApiResponse<void>;
			if (response.code === 200) {
				if (data?.id) {
					ElMessage.success('计划更新成功');
				} else {
					ElMessage.success('计划添加成功');
				}
				fetchPageData(searchParam.value);
				callback();
			} else {
				console.error('计划添加失败:', response.message);
			}
		} catch (error) {
			console.error('计划添加失败:', error);
		}
	};

	const deleteBaseDataPlan = async (id: string) => {
		try {
			const response = (await deleteBaseDataPlanApi({
				ids: [id]
			})) as unknown as ApiResponse<void>;
			if (response.code === 200) {
				ElMessage.success('删除成功');
				fetchPageData(searchParam.value);
			} else {
				console.error('计划删除失败:', response.message);
			}
		} catch (error) {
			console.error('计划删除失败:', error);
		}
	};
	const handleAddSubmit = (data, callback) => {
		console.log(data, 'params', data.planBeginTime[0]);
		console.log(data.keys);
		for (const item of data.keys) {
			if (!item.productId) {
				ElMessage.error('请选择产品');
				return false;
			}

			if (item.property === null || item.property === '' || item.property === undefined) {
				ElMessage.error('请选择属性');
				return false;
			}

			if (!item.processRouteId) {
				ElMessage.error('请选择路线');
				return false;
			}

			if (!item.planCount || item.planCount == 0) {
				ElMessage.error('请填写下发数量');
				return false;
			}


		}
		// type: data.type,
		// 	yield: data.yield,
		const planDetail = data.keys.map((item: any) => ({
			productId: item.productId,
			processRouteId: item.processRouteId,
			bomId: item.bomId,
			planCount: Number(item.planCount),
			type: data.type,
			status: 0,
			property: item.property
			// id
		}));
		const params = {
			...data,
			keys: undefined,
			planBeginTime: data.planBeginTime[0],
			planEndTime: data.planBeginTime[1],
			status: 0,
			productionPlanDetailDTO: planDetail
		};
		const url = data.id ? editBaseDataPlanApi : addBaseDataPlanApi;
		if (data.id) {
			params.productionPlanDetailDTO[0].id = data.keys[0].id;
		}
		url(params)
			.then((res) => {
				if (res.code === 200) {
					ElMessage.success(res.message);
					// currentItem.value = {};
					callback();
					fetchPageData();
				}
			})
			.catch((error) => {
				console.error('Error submitting form:', error);
			});
	};

	// 下发计划
	const handleIssue = async (data, type) => {
		console.log(data, 'ssss', type, 'sss');
		ElMessageBox.confirm('是否确认下发？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'success'
		})
			.then(async () => {
				await issuePlan([type]).then(async (res) => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return;
					}

					paginatedData.value = await updatePaginatedData(type.id);
					ElMessage.success('下发成功');
					fetchPageData()
				});
			})
			.catch(() => {
			});
	};

	const updatePaginatedData = async (planId: string) => {
		const newData = paginatedData.value.map(async (value) => {
			if (value.id === planId) {
				const child = await ProductionPlanDetailApi({ planId: planId });
				return { ...value, children: child.data.records };
			} else {
				return value;
			}
		});

		// 等待所有异步请求完成
		return Promise.all(newData);
	};
	return {
		searchParam,
		pageSize,
		current,
		pageTotal,
		paginatedData,
		searchFields,
		isLoading,
		productData,
		allRouteData,
		materialData,
		lineListAll,
		typeData,
		lineGroup,
		productAll,
		handleSearch,
		handleSizeChange,
		handleCurrentChange,
		addBaseDataPlan,
		deleteBaseDataPlan,
		handleAddSubmit,
		handleIssue
	};
}
